/**
 * 前后端集成示例 - 展示如何在Vue组件中使用API服务
 */

import type { CodeGenerationRequest } from "./codeGenerationApiService"
import type { DatabaseConnectionRequest } from "./databaseApiService"
import { ElMessage } from "element-plus"
import { reactive, ref } from "vue"
import { CodeGenerationApiService } from "./codeGenerationApiService"
import { DatabaseApiService } from "./databaseApiService"
import { TemplateApiService } from "./templateApiService"

// 示例1: 数据库连接测试
export function useDatabaseConnection() {
  const testingConnection = ref(false)
  const connectionConfig = reactive<DatabaseConnectionRequest>({
    type: "mysql",
    host: "localhost",
    port: 3306,
    database: "test_db",
    username: "root",
    password: "",
    charset: "utf8mb4",
    connectTimeout: 10000,
    useSSL: false,
    allowPublicKeyRetrieval: true
  })

  const testConnection = async () => {
    testingConnection.value = true
    try {
      const response = await DatabaseApiService.testConnection(connectionConfig)
      if (response.data.success) {
        ElMessage.success("数据库连接成功！")
        return true
      } else {
        ElMessage.error(response.data.message || "数据库连接失败")
        return false
      }
    } catch (error: any) {
      console.error("数据库连接测试失败:", error)
      ElMessage.error(error.message || "数据库连接测试失败")
      return false
    } finally {
      testingConnection.value = false
    }
  }

  return {
    connectionConfig,
    testingConnection,
    testConnection
  }
}

// 示例2: 获取模板列表
export function useTemplateList() {
  const loading = ref(false)
  const templates = ref<any[]>([])
  const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
  })

  const fetchTemplates = async (params?: any) => {
    loading.value = true
    try {
      const response = await TemplateApiService.getTemplates({
        current: pagination.current,
        size: pagination.size,
        ...params
      })

      templates.value = response.data.records
      pagination.total = response.data.total
      pagination.current = response.data.current
      pagination.size = response.data.size
    } catch (error: any) {
      console.error("获取模板列表失败:", error)
      ElMessage.error("获取模板列表失败")
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    templates,
    pagination,
    fetchTemplates
  }
}

// 示例3: 代码生成进度监控
export function useCodeGeneration() {
  const generating = ref(false)
  const progress = ref(0)
  const status = ref<"PENDING" | "RUNNING" | "COMPLETED" | "FAILED">("PENDING")
  const taskId = ref<string>("")

  const generateCode = async (request: CodeGenerationRequest) => {
    generating.value = true
    progress.value = 0
    status.value = "PENDING"

    try {
      // 启动生成任务
      const response = await CodeGenerationApiService.generateCode(request)
      taskId.value = response.data.taskId

      // 轮询进度
      const progressInterval = setInterval(async () => {
        try {
          const progressResponse = await CodeGenerationApiService.getProgress(taskId.value)
          const progressData = progressResponse.data

          progress.value = progressData.progress
          status.value = progressData.status

          if (status.value === "COMPLETED") {
            clearInterval(progressInterval)
            generating.value = false
            ElMessage.success("代码生成完成！")

            // 自动下载
            if (progressData.downloadUrl) {
              window.open(progressData.downloadUrl, "_blank")
            }
          } else if (status.value === "FAILED") {
            clearInterval(progressInterval)
            generating.value = false
            ElMessage.error(`代码生成失败: ${progressData.message}`)
          }
        } catch (error) {
          console.error("获取生成进度失败:", error)
        }
      }, 2000)

      // 5分钟超时保护
      setTimeout(() => {
        if (generating.value) {
          clearInterval(progressInterval)
          generating.value = false
          ElMessage.error("代码生成超时")
        }
      }, 5 * 60 * 1000)
    } catch (error: any) {
      console.error("启动代码生成失败:", error)
      ElMessage.error(error.message || "启动代码生成失败")
      generating.value = false
    }
  }

  const cancelGeneration = async () => {
    if (taskId.value) {
      try {
        await CodeGenerationApiService.cancelGeneration(taskId.value)
        generating.value = false
        status.value = "FAILED"
        ElMessage.info("已取消代码生成")
      } catch (error) {
        console.error("取消生成失败:", error)
      }
    }
  }

  return {
    generating,
    progress,
    status,
    taskId,
    generateCode,
    cancelGeneration
  }
}

// 示例4: 错误处理和重试机制
export function useApiWithRetry() {
  const retryCount = ref(0)
  const maxRetries = 3

  const callApiWithRetry = async <T>(
    apiCall: () => Promise<T>,
    retryDelay: number = 1000
  ): Promise<T> => {
    try {
      retryCount.value = 0
      return await apiCall()
    } catch (error: any) {
      console.error(`API调用失败 (尝试 ${retryCount.value + 1}/${maxRetries}):`, error)

      if (retryCount.value < maxRetries - 1) {
        retryCount.value++

        // 等待后重试
        await new Promise(resolve => setTimeout(resolve, retryDelay))
        return callApiWithRetry(apiCall, retryDelay * 2) // 指数退避
      } else {
        // 达到最大重试次数
        ElMessage.error(`请求失败，已重试 ${maxRetries} 次`)
        throw error
      }
    }
  }

  return {
    retryCount,
    callApiWithRetry
  }
}

// 在Vue组件中的使用示例
/*
<script setup lang="ts">
import { useDatabaseConnection, useTemplateList, useCodeGeneration } from '@/pages/apiGenerator/services/integrationExample'

// 使用数据库连接功能
const { connectionConfig, testingConnection, testConnection } = useDatabaseConnection()

// 使用模板列表功能
const { loading, templates, pagination, fetchTemplates } = useTemplateList()

// 使用代码生成功能
const { generating, progress, status, generateCode, cancelGeneration } = useCodeGeneration()

// 页面加载时获取模板列表
onMounted(() => {
  fetchTemplates()
})

// 处理数据库连接测试
const handleTestConnection = async () => {
  const success = await testConnection()
  if (success) {
    // 连接成功后的逻辑
    console.log('可以继续后续操作')
  }
}

// 处理代码生成
const handleGenerateCode = async () => {
  const request: CodeGenerationRequest = {
    templateId: 1,
    projectName: 'my-project',
    packageName: 'com.example.myproject',
    author: 'Developer',
    description: 'Generated project',
    tableIds: [1, 2, 3],
    features: {
      enableSwagger: true,
      enableSecurity: true,
      enableRedis: false,
      enableValidation: true,
      enablePageHelper: true
    }
  }

  await generateCode(request)
}
</script>
*/
